package com.open.pokergames.texas.view.cards5

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.gyf.immersionbar.ImmersionBar
import com.open.pokergames.R
import com.open.pokergames.comm.repository.cache.LocalCache
import com.open.pokergames.conn.bean.Message
import com.open.pokergames.conn.bean.Player
import com.open.pokergames.conn.bean.RoomMsg
import com.open.pokergames.conn.bean.WsConstant
import com.open.pokergames.conn.websocket.MessageManager
import com.open.pokergames.texas.repository.entity.RoomIM
import com.sinothk.android.utils.XUtils
import kotlinx.android.synthetic.main.activity_room_detail_5.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


abstract class Room5DetailBaseActivity : Room5DetailCommActivity(), View.OnClickListener {

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_HOME -> return true
            KeyEvent.KEYCODE_BACK -> return true
            KeyEvent.KEYCODE_CALL -> return true
            KeyEvent.KEYCODE_SYM -> return true
            KeyEvent.KEYCODE_VOLUME_DOWN -> return true
            KeyEvent.KEYCODE_VOLUME_UP -> return true
            KeyEvent.KEYCODE_STAR -> return true
        }
        return super.onKeyDown(keyCode, event)
    }

    protected fun exitRoom() {
        imExitRoom()
        EventBus.getDefault().unregister(this)
        finish()
    }

    protected fun standSeeRoom() {
        imStandSeeRoom()
        EventBus.getDefault().unregister(this)
        finish()
    }

    protected fun stopRoom() {
        imStopRoom()
        EventBus.getDefault().unregister(this)
        finish()
    }

    protected fun releaseRoom() {
        imReleaseRoom()
        EventBus.getDefault().unregister(this)
        setResult(WsConstant.TYPE_RM.TYPE_ROOM_RELEASE_BACK, intent)
        finish()
    }

    /**
     * =================================   收到消息   =============================
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun imCallback(roomMsg: RoomMsg?) {
        if (roomMsg == null) {
            return
        }

        try {
            receiveRoomMsg(roomMsg)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_room_detail_5)
        // 标题处理
        ImmersionBar.with(this)
            .keyboardEnable(false)
            .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
            .init()
        roomNum = intent.getStringExtra("roomNum") as String
        roomName = intent.getStringExtra("roomName") as String

        EventBus.getDefault().register(this)

        initRoom()
        setListener()
//        viewModel!!.getGroupMemberByRoomNum(roomNum!!)
    }

    @SuppressLint("SetTextI18n")
    private fun initRoom() {
        userLogin = LocalCache.getUser()
        if (XUtils.string().isEmpty(roomNum) || userLogin == null) {
            XUtils.toast().show("房间数据异常")
            finish()
            return
        }
        roomNameTv.text = "[${XUtils.string().getNotNullValue(roomName)}]"

        imEnterRoom()
    }

    private fun setListener() {
        backBtn.setOnClickListener(this)
        openGameBtn.setOnClickListener(this)

        AReadyView.setOnClickListener(this)
        BReadyView.setOnClickListener(this)
        CReadyView.setOnClickListener(this)
        DReadyView.setOnClickListener(this)
        EReadyView.setOnClickListener(this)
//        FReadyView.setOnClickListener(this)
//        GReadyView.setOnClickListener(this)
//        HReadyView.setOnClickListener(this)
//        IReadyView.setOnClickListener(this)
        // 游戏操作按钮
        giveUpView.setOnClickListener(this)
        seeCardView.setOnClickListener(this)
        addCoinItem.setOnClickListener(this)
    }

    override fun onClick(v: View) {

        // 预备界面控制
        controlReadyView(v)

        playOpt(v)

        when (v) {
            openGameBtn -> {
                if (roomIM!!.players.size < 2) {
                    XUtils.toast().show("参与人数不能少2人")
                    return
                }

                if (roomIM!!.state != 0) {
                    XUtils.toast().show("当前不是入座状态")
                    return
                }

                // 开始游戏
                imOpenGame()
            }
            backBtn -> {
                showLeftBtn()
            }
        }
    }

    abstract fun showLeftBtn()

    private fun playOpt(v: View) {
        timerPlayOpt.cancel()

        when (v) {
            giveUpView -> {// 弃牌
                imGiveUpCard()
            }
            seeCardView -> {// 看牌或跟注
                imSeeCardOrFlowAdd(doFlowAdd)
            }
            addCoinItem -> {// 加注
                showAddCoinDialog()
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showAddCoinDialog() {
        if (roomIM == null || roomIM!!.players.size == 0) {
            XUtils.toast().show("房间[roomIM]信息有误")
            return
        }
        var player: Player? = null
        roomIM!!.players.forEach { (_, value) ->
            if (userLogin!!.account == value.account) {
                player = value!!
            }
        }

        if (player == null) {
            XUtils.toast().show("用户[player]信息有误")
            return
        }
        val minValue = 0
        val maxValue = player!!.ownCoins

        if (maxValue < minValue) {
            XUtils.toast().show("积分不足")
            return
        }

        // 满足条件，显示加注框
        val builder: AlertDialog.Builder = AlertDialog.Builder(this)
        val inflater = LayoutInflater.from(this)
        val rootView: View = inflater.inflate(R.layout.play_add_coins_dialog, null)
        val cancelBtn: Button = rootView.findViewById(R.id.cancelBtn)
        val okBtn: Button = rootView.findViewById(R.id.okBtn)

        val contentView: LinearLayout = rootView.findViewById(R.id.contentView)
        val mySeekBar: SeekBar = rootView.findViewById(R.id.seekBar)

        val selectedValueTv: TextView = rootView.findViewById(R.id.selectedValueTv)
        val minValueTv: TextView = rootView.findViewById(R.id.minValueTv)
        val maxValueTv: TextView = rootView.findViewById(R.id.maxValueTv)


        var selectedValue = minValue

        minValueTv.text = "$minValue"
        maxValueTv.text = "$maxValue"
        selectedValueTv.text = "$selectedValue"

//        mySeekBar.min = minValue
        mySeekBar.max = maxValue

        val defValue = (roomIM!!.roomCurrCast - player!!.preCast).toInt()
        mySeekBar.progress = defValue

        mySeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                selectedValueTv.text = "$progress"
                selectedValue = progress
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }
        })

//        val btn_sure: Button = v.findViewById<View>(R.id.dialog_btn_sure) as Button
//        val btn_cancel: Button = v.findViewById<View>(R.id.dialog_btn_cancel) as Button
        //builer.setView(v);//这里如果使用builer.setView(v)，自定义布局只会覆盖title和button之间的那部分
        val dialog: Dialog = builder.create()
        dialog.show()
        dialog.window!!.setContentView(contentView) //自定义布局应该在这里添加，要在dialog.show()的后面

        //dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置

        cancelBtn.setOnClickListener {
            dialog.dismiss()
        }
        okBtn.setOnClickListener {
            if (selectedValue >= defValue) {
                dialog.dismiss()
                imAddCoin(selectedValue)
            } else {
                XUtils.toast().show("加注积分应该大于${defValue}个积分")
            }
        }
    }

    private fun controlReadyView(v: View) {// 入座控制
        when (v) {
            AReadyView -> {
                imSitDown("A")
            }
            BReadyView -> {
                imSitDown("B")
            }
            CReadyView -> {
                imSitDown("C")
            }
            DReadyView -> {
                imSitDown("D")
            }
            EReadyView -> {
                imSitDown("E")
            }
//            FReadyView -> {
//                imSitDown("F")
//            }
//            GReadyView -> {
//                imSitDown("G")
//            }
//            HReadyView -> {
//                imSitDown("H")
//            }
//            IReadyView -> {
//                imSitDown("I")
//            }
        }
    }

    // =========================================== 发消息 ============

    private fun imEnterRoom() {
        val roomMsg = RoomMsg()
        roomMsg.roomNum = roomNum
        roomMsg.type = WsConstant.TYPE_RM.TYPE_ROOM_ENTER
        roomMsg.account = userLogin!!.account
        MessageManager.obj().sendMsg(Message(WsConstant.MsgType.TYPE_ROOM, JSON.toJSONString(roomMsg)))
    }

    private fun imExitRoom() {
        val roomMsg = RoomMsg()
        roomMsg.roomNum = roomNum
        roomMsg.type = WsConstant.TYPE_RM.TYPE_ROOM_EXIT
        roomMsg.account = userLogin!!.account
        MessageManager.obj().sendMsg(Message(WsConstant.MsgType.TYPE_ROOM, JSON.toJSONString(roomMsg)))
    }

    private fun imStandSeeRoom() {
        val roomMsg = RoomMsg()
        roomMsg.roomNum = roomNum
        roomMsg.type = WsConstant.TYPE_RM.TYPE_ROOM_POKER_STAND_SEE
        roomMsg.account = userLogin!!.account
        MessageManager.obj().sendMsg(Message(WsConstant.MsgType.TYPE_ROOM, JSON.toJSONString(roomMsg)))
    }

    private fun imStopRoom() {
        val roomMsg = RoomMsg()
        roomMsg.roomNum = roomNum
        roomMsg.type = WsConstant.TYPE_RM.TYPE_ROOM_POKER_STOP_GAME
        roomMsg.account = userLogin!!.account
        MessageManager.obj().sendMsg(Message(WsConstant.MsgType.TYPE_ROOM, JSON.toJSONString(roomMsg)))
    }

    private fun imReleaseRoom() {
        val roomMsg = RoomMsg()
        roomMsg.roomNum = roomNum
        roomMsg.type = WsConstant.TYPE_RM.TYPE_ROOM_RELEASE
        roomMsg.account = userLogin!!.account
        MessageManager.obj().sendMsg(Message(WsConstant.MsgType.TYPE_ROOM, JSON.toJSONString(roomMsg)))
    }

    private fun imSitDown(seatNum: String) {
        val roomMsg = RoomMsg()
        roomMsg.roomNum = roomNum
        roomMsg.type = WsConstant.TYPE_RM.TYPE_ROOM_SIT_DOWN
        roomMsg.account = userLogin!!.account

        roomMsg.seatNum = seatNum

//        val player = Player()
//        // 进本信息
//        player.account = userLogin!!.account
//        player.playerName = userLogin!!.userName
//        player.playerAvatar = userLogin!!.userAvatar
//        // 座位
//        player.seatNum = seatNum
////        player.ownCoins = groupMember!!.memberCoins
//
//        roomMsg.body = player

        MessageManager.obj().sendMsg(Message(WsConstant.MsgType.TYPE_ROOM, JSON.toJSONString(roomMsg)))
    }

    private fun imOpenGame() {
        val roomMsg = RoomMsg()
        roomMsg.roomNum = roomNum
        roomMsg.type = WsConstant.TYPE_RM.TYPE_ROOM_START
        MessageManager.obj().sendMsg(Message(WsConstant.MsgType.TYPE_ROOM, JSON.toJSONString(roomMsg)))
    }

    private fun imSeeCardOrFlowAdd(doFlowAdd: Boolean) {// 跟注或看牌
        val roomMsg = RoomMsg()
        roomMsg.roomNum = roomNum
        if (doFlowAdd) {
            roomMsg.type = WsConstant.TYPE_RM.TYPE_ROOM_PLAYING_FLOW
        } else {
            roomMsg.type = WsConstant.TYPE_RM.TYPE_ROOM_PLAYING_SEE_CARD
        }
        roomMsg.body = getCurrPlayer()!!.seatNum

        MessageManager.obj().sendMsg(Message(WsConstant.MsgType.TYPE_ROOM, JSON.toJSONString(roomMsg)))
    }

    private fun imAddCoin(addCoin: Int) {
        val roomMsg = RoomMsg()
        roomMsg.roomNum = roomNum
        roomMsg.type = WsConstant.TYPE_RM.TYPE_ROOM_PLAYING_ADD

        val player = Player()
        player.account = userLogin!!.account
        player.seatNum = getCurrPlayer()!!.seatNum
        player.preAddCast = addCoin
        roomMsg.body = player

        MessageManager.obj().sendMsg(Message(WsConstant.MsgType.TYPE_ROOM, JSON.toJSONString(roomMsg)))
    }

    fun imGiveUpCard() {// 弃牌
        val roomMsg = RoomMsg()
        roomMsg.roomNum = roomNum
        roomMsg.type = WsConstant.TYPE_RM.TYPE_ROOM_PLAYING_CANCEL
        roomMsg.seatNum = getCurrPlayer()!!.seatNum
        MessageManager.obj().sendMsg(Message(WsConstant.MsgType.TYPE_ROOM, JSON.toJSONString(roomMsg)))
    }

    /**
     * =================================  房间所有消息    =============================
     */
    private fun receiveRoomMsg(roomMsg: RoomMsg?) {
        if (roomMsg == null || baseContext == null) {
            return
        }

        when (roomMsg.type) {
            WsConstant.TYPE_RM.TYPE_ROOM_RELEASE_BACK -> {
                setResult(WsConstant.TYPE_RM.TYPE_ROOM_RELEASE_BACK)
                finish()
            }
            WsConstant.TYPE_RM.TYPE_ROOM_ALL_ERROR_BACK -> {
                XUtils.toast().show(roomMsg.errorInfo)
            }
            else -> {
                roomIM = JSON.parseObject(roomMsg.body.toString(), RoomIM::class.java)
                // 显示整体界面
                showRoomView(roomIM!!)
            }
        }
    }

//    abstract fun showReadyView(sitEnable: Boolean)

    abstract fun showRoomView(roomIM: RoomIM)
    abstract fun hideAllRunningView()
    abstract fun showAllReadyView()
    abstract fun hideAllReadyView()
    abstract fun enableReadyView()
    abstract fun showAllRunningView()
    abstract fun showPublicPoker(hasPubPokers: Boolean)


}